package org.crystal.tradecraft.model.binance.param;

import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

import org.crystal.tradecraft.model.binance.enumeration.Interval;

import lombok.Builder;

@Builder(toBuilder = true)
public record KLineQuery(
	String symbol,
	Interval interval,
	Instant startTime,
	Instant endTime,
	String timeZone,
	Integer limit
) {

    public static final int LIMIT_MAX = 1000;
    
    public Map<String, Object> toMap() {
		Map<String, Object> map = new HashMap<>();
        map.put("symbol", symbol);
		map.put("interval", interval.getExpression());
		map.put("timeZone", Optional.ofNullable(timeZone).orElse("0"));
		map.put("limit", Optional.ofNullable(limit).map(Integer::intValue).orElse(LIMIT_MAX));
		if (Objects.nonNull(startTime)) map.put("startTime", startTime.toEpochMilli());
		if (Objects.nonNull(endTime)) map.put("endTime", endTime.toEpochMilli());
		return map;
    }

	public Map<String, Object> toFirstQueryMap() {
		return Map.of(
			"symbol", symbol,
			"interval", interval.getExpression(),
			"timeZone", Optional.ofNullable(timeZone).orElse("0"),
			"endTime", Optional.ofNullable(endTime).map(Instant::toEpochMilli).orElseGet(() -> Instant.now().minus(interval.getDuration()).toEpochMilli()),
			"limit", Optional.ofNullable(limit).map(Integer::intValue).orElse(LIMIT_MAX)
			);
	}
}
